<?php
/*
File: catagoriesnew.php - redone version of catagories.php
Version: 1.0
Date created: 26-07-2008
Last Edited : 26-07-2008
Author: Craig G Smith<craig@joomla-host.co.za
*/

defined( 'JOSCOM_VERSION' ) or die( 'Direct Access to this location is not allowed.' );

if (defined( '_OSCOMMERCE_LOADED' )) {
    if (!DB_SHARED) {
      tep_db_connect() or die('Unable to connect to database server!');
    }
    global $category_links, $languages_id, $cPath, $cPath_array, $current_category_id;
    global $request_type, $lng, $cart, $currencies, $language, $navigation, $breadcrumb;
  } else {
    require(DIR_WS_COMPONENT . 'includes/application_top.php');
  }

//options here is to have simply the categorie tree with categories and subcategories...
$action = isset($_REQUEST['action'])?$_REQUEST['action']:'';

//to be moved to functions section in general.php
function jh_TreeRecurse( $id, $indent, $list, &$children, $maxlevel=9999, $level=0, $type=1 ) {

	if (@$children[$id] && $level <= $maxlevel) {
		foreach ($children[$id] as $v) {
			$id = $v->categories_id;

			if ( $type ) {
				$pre 	= '<sup>L</sup>&nbsp;';
				$spacer = '<sup>L</sup>.....&nbsp;&nbsp;';
			} else {
				$pre 	= '- ';
				$spacer = '&nbsp;&nbsp;';
			}

			if ( $v->parent == 0 ) {
				$txt 	= $v->categories_name;
			} else {
				$txt 	= $pre . $v->categories_name;
			}
			$pt = $v->parent_id;
			$list[$id] = $v;
			$list[$id]->treename = "$indent$txt";
			$list[$id]->children = count( @$children[$id] );

			$list = jh_TreeRecurse( $id, $indent . $spacer, $list, $children, $maxlevel, $level+1, $type );
		}
	}
	return $list;
}
?>

<link rel="stylesheet" type="text/css" href="<?php echo DIR_WS_COMPONENT ?>includes/stylesheet.css">
<script language="javascript" src="<?php echo DIR_WS_COMPONENT ?>includes/general.js"></script>

<!-- header //-->
<?php require(DIR_WS_INCLUDES . 'header.php'); ?>

<?php
//this is needed almost on all parts of the site:
$database->setQuery("select customers_group_id, customers_group_name from " . TABLE_CUSTOMERS_GROUPS . " order by customers_group_name");
$cgp = $database->loadObjectList();
$cgnarr = array();
foreach($cgp as $cgrp){
$cgnarr[$cgrp->customers_group_id] = $cgrp->customers_group_name;
}

switch($action){

case "delete":
$cids = $_POST['cid'];
foreach($cids as $cid){


          $categories_id = tep_db_prepare_input($cid);

          $categories = tep_get_category_tree($categories_id, '', '0', '', true);
          $products = array();
          $products_delete = array();

          for ($i=0, $n=sizeof($categories); $i<$n; $i++) {
            $product_ids_query = tep_db_query("select products_id from " . TABLE_PRODUCTS_TO_CATEGORIES . " where categories_id = '" . (int)$categories[$i]['id'] . "'");

            while ($product_ids = tep_db_fetch_array($product_ids_query)) {
              $products[$product_ids['products_id']]['categories'][] = $categories[$i]['id'];
            }
          }

          reset($products);
          while (list($key, $value) = each($products)) {
            $category_ids = '';

            for ($i=0, $n=sizeof($value['categories']); $i<$n; $i++) {
              $category_ids .= "'" . (int)$value['categories'][$i] . "', ";
            }
            $category_ids = substr($category_ids, 0, -2);

            $check_query = tep_db_query("select count(*) as total from " . TABLE_PRODUCTS_TO_CATEGORIES . " where products_id = '" . (int)$key . "' and categories_id not in (" . $category_ids . ")");
            $check = tep_db_fetch_array($check_query);
            if ($check['total'] < '1') {
              $products_delete[$key] = $key;
            }
          }

// removing categories can be a lengthy process
          tep_set_time_limit(0);
          for ($i=0, $n=sizeof($categories); $i<$n; $i++) {
            tep_remove_category($categories[$i]['id']);
          }

          reset($products_delete);
          while (list($key) = each($products_delete)) {
            tep_remove_product($key);
          }




}
$url = tep_href_link("catprodnew.php", 'msg=' . TEXT_UPDATE_COMPLETE);
  tep_redirect($url);
break;
case "save":
case "editsave":

//ok now we need to handle if it is an update or a new product!!!?
if (isset($_POST['categories_id'])) $categories_id = tep_db_prepare_input($_POST['categories_id']);

        // BOF Separate Pricing Per Customer, hide categories from groups
        $hide_cats_from_these_groups = '@,';
          if ( $_POST['hide_from'] ) { // if any of the checkboxes are checked
		        foreach($_POST['hide_from'] as $val) {
		        $hide_cats_from_these_groups .= tep_db_prepare_input($val).','; 
		        } // end foreach
	        }
				 $hide_cats_from_these_groups = substr($hide_cats_from_these_groups,0,strlen($hide_cats_from_these_groups)-1);

$sort_order = tep_db_prepare_input($_POST['sort_order']);

$sql_data_array = array('sort_order' => (int)$sort_order,
'categories_hide_from_groups' => $hide_cats_from_these_groups);

if($action == 'save'){
$insert_sql_data = array('parent_id' => $_POST['cPath'],
                                   'date_added' => 'now()',
                                   'last_modified' => 'now()');
$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
tep_db_perform(TABLE_CATEGORIES, $sql_data_array);
$categories_id = tep_db_insert_id();
}else{
$insert_sql_data = array('parent_id' => $_POST['cPath'],
                                   'last_modified' => 'now()');
$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
tep_db_perform(TABLE_CATEGORIES, $sql_data_array, 'update', "categories_id = '" . (int)$categories_id . "'");
}

$languages = tep_get_languages();
        for ($i=0, $n=sizeof($languages); $i<$n; $i++) {

          $categories_name_array = $_POST['categories_name'];
          $categories_description_array = $_POST['categories_description'];

          $language_id = $languages[$i]['id'];

          $sql_data_array = array('categories_name' => tep_db_prepare_input($categories_name_array[$language_id]),
                                  'categories_description' => tep_db_prepare_input($categories_description_array[$language_id]));

          if ($action == 'save') {
            $insert_sql_data = array('categories_id' => $categories_id,
                                     'language_id' => $languages[$i]['id']);

            $sql_data_array = array_merge($sql_data_array, $insert_sql_data);

            tep_db_perform(TABLE_CATEGORIES_DESCRIPTION, $sql_data_array);
          } elseif ($action == 'editsave') {
            tep_db_perform(TABLE_CATEGORIES_DESCRIPTION, $sql_data_array, 'update', "categories_id = '" . (int)$categories_id . "' and language_id = '" . (int)$languages[$i]['id'] . "'");
          }
        }
        
        if ($categories_image = new upload('categories_image', DIR_FS_CATALOG_IMAGES)) {
    
          tep_db_query("update " . TABLE_CATEGORIES . " set categories_image = '" . tep_db_input($categories_image->filename) . "' where categories_id = '" . (int)$categories_id . "'");
         // print_r($categories_image);
          //this is now to test watermark the image:::
          //echo $categories_image->filename;
          AddWatermark($categories_image->filename);
          //die();
        }

$url = tep_href_link("catprodnew.php", 'msg=' . TEXT_UPDATE_COMPLETE);
  tep_redirect($url);
break;
case "edit":
$cid = $_GET['cid'][0];
if($cid > 0){
$database->setQuery("select c.*, cd.* from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id = cd.categories_id and c.categories_id = '$cid'");
$tarr = $database->loadObjectList();
$curcat = $tarr[0];
foreach($curcat as $key=>$value){
$$key = $value;
}
}
echo tep_draw_form('adminForm', tep_href_link("catprodnew.php"), "POST", 'enctype="multipart/form-data"');
if($cid > 0){
echo "<input type='hidden' name='categories_id' value='$cid'>";
echo "<input type='hidden' name='action' value='editsave'>";
}else{
echo "<input type='hidden' name='action' value='save'>";
}
$languages = tep_get_languages();
//for ($i=0, $n=sizeof($languages); $i<$n; $i++) {

//ok so now we are ready to display the form!!!! -> lets!!!->
?>
<table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td class="pageHeading"><?php echo HEADING_TITLE_EDIT_ADD_CAT; ?></td>
            <td class="pageHeading" align="right"></td>
          </tr>
</table>

<table class="adminlist" cellspacing="1">
<tr><th colspan="2"><?php echo TEXT_EDIT_CATEGORIES_NAME ?></th></tr>
<?php
$r = 0;
for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
?>
<tr class="dataTableRow<?php echo $r;?>" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)">
<td class="maincol" valign="top"><?php echo tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']); ?>&nbsp;</td>
<td class="maincol" valign="top"><input type="text" name="categories_name[<?php echo $languages[$i]['id'];?>]" value="<?php echo tep_get_category_name($categories_id, $languages[$i]['id']);?>"></td> </tr>
<?php
$r = 1 - $r;
}?>
<tr><th colspan="2"><?php echo TEXT_CATEGORIES_DESC;?></th></tr>
<?php
$r = 0;
for ($i=0, $n=sizeof($languages); $i<$n; $i++) {
?>
<tr class="dataTableRow<?php echo $r;?>" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)">
<td class="maincol" valign="top"><?php echo tep_image(DIR_WS_CATALOG_LANGUAGES . $languages[$i]['directory'] . '/images/' . $languages[$i]['image'], $languages[$i]['name']); ?>&nbsp;</td>
<td class="maincol" valign="top">
<?php
editorArea( 'categories_description[' . $languages[$i]['id'] . ']',   stripslashes(tep_get_category_description($categories_id, $languages[$i]['id'])) , 'categories_description[' . $languages[$i]['id'] . ']', '400', '200', '', '20' ) ; ?>
</td></tr>
<?php
$r = 1 - $r;
}
?><tr class="dataTableRow0"><td><?php echo TEXT_EDIT_CATEGORIES_PARENT ?></td><td><?php echo tep_draw_pull_down_menu('cPath', tep_get_category_tree(), (isset($parent_id)?$parent_id:''));?></td></tr>
<tr><th colspan="2"><?php echo TEXT_HIDE_CATEGORIES_FROM_GROUPS;?></th></tr>
<?php
$hide_cat_from_groups_array = explode(',', $categories_hide_from_groups);
$hide_cat_from_groups_array = array_slice($hide_cat_from_groups_array, 1);
$r=0;
foreach ($cgnarr as $key=>$value){
?>
<tr class="dataTableRow<?php echo $r;?>" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)">
<td><?php echo $value;?></td><td><input type="checkbox" name="hide_from[]" value="<?php echo $key;?>" <?php
if (in_array($key, $hide_cat_from_groups_array)){
echo " CHECKED";
}
?>></td></tr>
<?php
$r = 1-$r;
}
?>
<tr class="dataTableRow0" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)">
<td><?php echo TEXT_CATEGORIES_IMAGE;?></td>
<td><input type="file" name="categories_image">  <?php echo $categories_image;?></td></tr>
<tr class="dataTableRow1" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)">
<td><?php echo TEXT_SORT_ORDER;?></td>
<td><input type="text" name="sort_order" value="<?php echo $sort_order;?>"></td></tr>

<tr><th colspan="2" align="right"><?php echo tep_image_submit("button_save.gif", IMAGE_SAVE);?></th>
</tr>
</form>
</table>
<?php
//tep_get_products_description($pInfo->products_id, $languages[$i]['id']);
break;

default:

$database->setQuery("select c.categories_id, cd.categories_name, cd.categories_description, c.categories_image, c.parent_id, c.sort_order, c.date_added, c.last_modified, c.categories_hide_from_groups from " . TABLE_CATEGORIES . " c, " . TABLE_CATEGORIES_DESCRIPTION . " cd where c.categories_id = cd.categories_id and cd.language_id = '" . (int)$languages_id . "' order by c.sort_order, cd.categories_name");
$rows = $database->loadObjectList();
//echo '<pre>';
//print_r($result);

$children = array ();

    // first pass - collect children
    foreach ($rows as $v)
    {
        $pt = $v->parent_id;
        $list = @$children[$pt] ? $children[$pt] : array ();
        array_push($list, $v);
        $children[$pt] = $list;
    }
    
    $list = jh_TreeRecurse(0, '', array (), $children);
    
    //print_r($list);
  //  echo '</pre>';
    $total = count($list);
    require_once ($GLOBALS['mosConfig_absolute_path'] . '/administrator/includes/pageNavigation.php');
    $limit = $mainframe->getUserStateFromRequest("viewlistlimit", 'limit',25);
    $limitstart = $mainframe->getUserStateFromRequest("view{$option}limitstart", 'limitstart', 0);
    
    $pageNav = new mosPageNav($total, $limitstart, $limit);
    $catlist = array_slice($list, $pageNav->limitstart, $pageNav->limit);
    //print_r($catlist);
    echo tep_draw_form('adminForm', tep_href_link("catprodnew.php"), "POST");
?>
<input type="hidden" name="limitstart">
<table border="0" width="100%" cellspacing="0" cellpadding="0">
          <tr>
            <td class="pageHeading"><?php echo HEADING_TITLE; ?></td>
            <td class="pageHeading" align="right"></td>
          </tr>
</table>



<table class="adminlist" cellspacing="1">
			<thead>
				<tr>
					<th width="5">
						#					</th>
					<th width="5">

						<input type="checkbox" name="toggle" value="" onclick="checkAll(<?php echo count($list) + 1;?>);" />
					</th>
					<th width="30%"><?php echo TEXT_CATEGORIES;?> </th>
					<th width="20%"><?php echo TEXT_DATE_ADDED;?> </th>
					<th width="20%"><?php echo TEXT_DATE_MODIFIED;?> </th>
					<th width="*"><?php echo TEXT_HIDDEN_FROM;?></th>
				</tr>
			<thead>
			
<?php 
$row = 0;
$cnt = 1;
foreach($catlist as $cat){
?>
<tr class="dataTableRow<?php echo $row;?>" onmouseover="rowOverEffect(this)" onmouseout="rowOutEffect(this)">
<td><?php echo $cnt;?></td>
<td><input type="checkbox" id='cb<?php echo $cnt;?>' name="cid[]" value="<?php echo $cat->categories_id;?>"></td>
<td><a href="<?php echo tep_href_link("catprodnew.php", "action=edit&cid[]=" . $cat->categories_id);?>"><?php echo $cat->treename;?></a></td>
<td><?php echo $cat->date_added;?></td>
<td><?php echo $cat->last_modified;?></td>
<td><?php

$hidarr = explode(",", $cat->categories_hide_from_groups);
if(count($hidarr > 1)){
unset($hidarr[0]);
foreach($hidarr as $group){
echo "<li>" . $cgnarr[$group] . "</li>";
}
}
?></td>
</tr>
<?php
$row = 1 - $row;
$cnt++;
}			
?>
<tr><th align = "center" colspan = "6"><center><?php echo $pageNav->writePagesLinks(); ?> <?php echo $pageNav->writeLimitBox(); ?>
                            </th>
                        </tr>

                        <tr>
                            <td align = "center" colspan = "6"> <center><?php echo $pageNav->writePagesCounter(); ?>
                            </td>
                        </tr>
                        
                        <tr><td align = "right" colspan="4"><?php echo TEXT_DELETE_WARN;?> </td><td cospan="2" align="right"><a href="<?php echo tep_href_link("catprodnew.php", "action=edit");?>"><?php echo tep_image_button("button_insert.gif", IMAGE_INSERT);?></a> <?php echo tep_image_submit("button_delete.gif", IMAGE_DELETE);?><input type="hidden" name="action" value="delete"></tD></tr>
</table></form>

<?php

break;
}

?>





<?php require(DIR_WS_INCLUDES . 'footer.php');
  require(DIR_WS_INCLUDES . 'application_bottom.php');
  if (!DB_SHARED) {
    global $database, $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix;
    $database = new database( $mosConfig_host, $mosConfig_user, $mosConfig_password, $mosConfig_db, $mosConfig_dbprefix );
  }













